﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using OfficeOpenXml;

namespace Topro.Web.Controllers
{
    using Microsoft.AspNetCore.Hosting;
    using Topro.Application.Interface;
    using Topro.Entity.Enum;
    using Topro.Entity.Query;
    using Topro.Util;

    /// <summary>
    /// 报表控制器
    /// </summary>
    public class ReportController : BaseController
    {
        #region 注入
        /// <summary>
        /// 库存接口
        /// </summary>
        private readonly InventoryService _inventoryService;

        /// <summary>
        /// 
        /// </summary>
        private readonly IWebHostEnvironment _hostEnvironment;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="stockInService">库存接口</param>
        public ReportController(InventoryService inventoryService, IWebHostEnvironment hostEnvironment)
        {
            _inventoryService = inventoryService;
            _hostEnvironment = hostEnvironment;
        }
        #endregion

        /// <summary>
        /// 出入库报表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>DataGrid<StockInQueryResponse></returns>
        public JsonResult InventoryQuery(InventoryQuery query)
        {
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (DateUtil.IsDateTime(query.StartTime) && DateUtil.IsDateTime(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd 23:59:59");
                }
            }
            //状态
            query.Status = (int)InventoryStatus.完成;
            var list = _inventoryService.ReportInventoryQuery(query);

            return Json(list);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public IActionResult ExportExcel(InventoryQuery query)
        {
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (DateUtil.IsDateTime(query.StartTime) && DateUtil.IsDateTime(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd 23:59:59");
                }
            }

            //状态
            query.Status = (int)InventoryStatus.完成;

            var list = _inventoryService.ExportReportQuery(query);

            //文件名称
            var fileName = @$"{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
            //路径
            var filePath = Path.Combine(@$"{_hostEnvironment.WebRootPath}", fileName);
            //文件对象
            FileInfo file = new FileInfo(filePath);
            //是否存在
            if (file.Exists)
            {
                file.Delete();
            }
            //指定EPPlus使用非商业证书
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (ExcelPackage package = new ExcelPackage(file))
            {
                //创建sheet
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");

                //头部
                worksheet.Cells[1, 1].Value = "单据号";
                worksheet.Cells[1, 2].Value = "库位";
                worksheet.Cells[1, 3].Value = "料号";
                worksheet.Cells[1, 4].Value = "物料名称";
                worksheet.Cells[1, 5].Value = "数量";
                worksheet.Cells[1, 6].Value = "批号";
                worksheet.Cells[1, 7].Value = "等级";
                worksheet.Cells[1, 8].Value = "托盘";
                worksheet.Cells[1, 9].Value = "备注";
                worksheet.Cells[1, 10].Value = "创建时间";
                //行数
                int row = 2;

                foreach (var item in list)
                {
                    //单据号
                    worksheet.Cells[row, 1].Value = item.ResourceId;
                    //库位
                    worksheet.Cells[row, 2].Value = item.WarehouseUnitTostring;
                    //物料信息
                    worksheet.Cells[row, 3].Value = item.PartNo;
                    //物料信息
                    worksheet.Cells[row, 4].Value = item.ProductName;
                    //数量
                    if (item.IsContainer == (int)IsContainer.空)
                        worksheet.Cells[row, 5].Value = "";
                    else
                        worksheet.Cells[row, 5].Value = item.Qty;
                    //批号
                    worksheet.Cells[row, 6].Value = item.LotNo;
                    //等级
                    worksheet.Cells[row, 7].Value = item.Grade;
                    //托盘
                    if (item.IsContainer == (int)IsContainer.空)
                        worksheet.Cells[row, 8].Value = $"{item.ContainerCode}(空)";
                    else
                        worksheet.Cells[row, 8].Value = item.ContainerCode;
                    //备注
                    worksheet.Cells[row, 9].Value = item.Remark;
                    //创建时间
                    worksheet.Cells[row, 10].Value = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");

                    row++;
                }

                package.Save();
            }

            return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", fileName);
        }
    }
}
